package com.geekhalo.demo.enums.code.fix;


import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@MappedTypes(CodeBasedOrderStatus.class)
public class CodeBasedOrderStatusHandler extends BaseTypeHandler<CodeBasedOrderStatus> {

    /**
     * 将枚举类型转换为数据库存储的code
     * @param preparedStatement
     * @param i
     * @param t
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, CodeBasedOrderStatus t, JdbcType jdbcType) throws SQLException {
        preparedStatement.setInt(i, t.getCode());
    }

    /**
     * 数据库存储的code转换为枚举类型
     * @param resultSet
     * @param columnName
     * @return
     * @throws SQLException
     */
    @Override
    public CodeBasedOrderStatus getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        int code = resultSet.getInt(columnName);
        for (CodeBasedOrderStatus status : CodeBasedOrderStatus.values()){
            if (status.getCode() == code){
                return status;
            }
        }
        return null;
    }

    @Override
    public CodeBasedOrderStatus getNullableResult(ResultSet resultSet, int i) throws SQLException {
        int code = resultSet.getInt(i);
        for (CodeBasedOrderStatus status : CodeBasedOrderStatus.values()){
            if (status.getCode() == code){
                return status;
            }
        }
        return null;
    }

    @Override
    public CodeBasedOrderStatus getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        int code = callableStatement.getInt(i);
        for (CodeBasedOrderStatus status : CodeBasedOrderStatus.values()){
            if (status.getCode() == code){
                return status;
            }
        }
        return null;
    }
}
